package br.com.rapidrest.demo.web.engine.phonebook;

import java.io.Serializable;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.ejb.EJB;

import br.com.rapidrest.annotation.Inject;
import br.com.rapidrest.demo.domain.PhoneBook;
import br.com.rapidrest.demo.domain.PhoneEntry;
import br.com.rapidrest.demo.service.PhoneBookService;
import br.com.rapidrest.demo.web.engine.Home;
import br.com.rapidrest.util.MessagesBundle;

public class ViewPhoneBook implements Serializable {

	private static final long serialVersionUID = 6173745080453456123L;

	@Inject
	private MessagesBundle messages;

	@EJB
	private PhoneBookService phoneBookService;
	
	private PhoneBook phoneBook;
	
	public Object init(Long phoneBookId) {
		phoneBook = phoneBookService.findPhoneBook(phoneBookId);
		if (phoneBook == null) {
			return Home.class;
		}
		return null;
	}
	
	public List<PhoneEntry> getEntries() {
		List<PhoneEntry> entries = phoneBook.getEntries();
		Collections.sort(entries, new Comparator<PhoneEntry>() {

			@Override
			public int compare(PhoneEntry e1, PhoneEntry e2) {
				final Comparator<String> strComparator = String.CASE_INSENSITIVE_ORDER;
				int compare = strComparator.compare(e1.getName(), e2.getName());
				
				if (compare != 0) {
					return compare;
				}
				
				return strComparator.compare(e1.getPhone(), e2.getPhone());
			}

		});
		return entries;
	}

	public PhoneBook getPhoneBook() {
		return phoneBook;
	}

	public void setPhoneBook(PhoneBook phoneBook) {
		this.phoneBook = phoneBook;
	}

	public MessagesBundle getMessages() {
		return messages;
	}

}
